from rest_framework import serializers
from rest_framework.exceptions import APIException
from utils.password_hashlib import pwd_sha256
from . import models


class GetAdminsSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Admins
        fields = ['id', 'username', 'name', 'tel', 'email', 'is_active', 'date_add', 'date_lock', 'err_num',
                  'role', 'department']
        read_only_fields = ['id', 'username', 'name', 'tel', 'email', 'is_active', 'date_add', 'date_lock', 'err_num',
                            'role', 'department']

    role = serializers.SerializerMethodField()

    def get_role(self, obj):
        if obj.role:
            return {
                'id': obj.role.id,
                'name': obj.role.name
            }
        return None

    department = serializers.SerializerMethodField()

    def get_department(self, obj):
        if obj.department:
            return {
                'id': obj.department.id,
                'name': obj.department.name
            }
        return None


class AdminsSerializer(serializers.ModelSerializer):
    username = serializers.CharField(required=False, allow_blank=True)
    password = serializers.CharField(required=False, write_only=True, allow_blank=True)
    date_lock = serializers.DateTimeField(required=False)

    class Meta:
        model = models.Admins
        fields = ['id', 'username', 'password', 'name', 'tel', 'email', 'is_active', 'date_add', 'date_lock', 'err_num',
                  'role', 'department']

        extra_kwargs = {
            'id': {'read_only': True},
            'date_add': {'read_only': True},
            'err_num': {'read_only': True}
        }

    def create(self, validated_data):
        is_admin = models.Admins.objects.filter(username=validated_data.get('username')).first()
        if is_admin:
            raise APIException('管理员账号已经存在！', code=1404)
        pwd = pwd_sha256(validated_data.get('password'))
        validated_data['password'] = pwd
        admin = models.Admins.objects.create(**validated_data)
        return admin

    def update(self, instance, validated_data):
        if validated_data.get('password'):
            pwd = pwd_sha256(validated_data.get('password'))
            instance.password = pwd
        instance.name = validated_data.get('name')
        instance.tel = validated_data.get('tel')
        instance.email = validated_data.get('email')
        instance.is_active = validated_data.get('is_active')
        instance.date_lock = validated_data.get('date_lock')
        instance.role = validated_data.get('role')
        instance.department = validated_data.get('department')
        instance.save()
        return instance
